<?php
class PublicAction extends CommonAction
{
	
	/**
	 * 新用户注册
	 */
	public function register() {
		if ($this->isPost()) {
			$params = $_POST;
			
			$account = trim($params['account']);
			$pwd = trim($params['pwd']);
			$rePwd = trim($params['repwd']);
			
			if ($pwd != $rePwd)
				$this -> error('两次密码不一致！');
				
			$Model = new Model();
			$Model -> startTrans();
			
			$UserLogic = D('User', 'Logic'); 
			$regRet = $UserLogic -> doRegister();
			if (!$regRet)
				$this -> error($UserLogic -> getError());
			
			$initRet = $UserLogic -> initUserInfo($regRet, $account);
			if (!$initRet) {
				$Model -> rollback();
				$this -> error($UserLogic -> getError());
			}
			
			$Model -> commit();
			
			// 添加日志
			$ret = D('Log', 'Logic') -> addActionLog($regRet, $account, 1, '新用户注册，用户名：'. $account);
			//发送消息
			$msgRet = D('Message',  'Logic') -> systemMsg($regRet, 1);
			
			$this -> success('恭喜您，注册成功！','login');			
		} else {
			$this -> display();
		}
	
	}
	
	/**
	 * 用户登录页面
	 */
	public function login() {
	
		echo "登录界面！";
	}
	
	/**
	 * 处理用户登录
	 */
	public function doLogin() {
		$Model = D('User');
		$account = trim($_POST['account']);
		$pwd = trim($_POST['pwd']);
		
		$ret = 0;
		$errMsg = '';
		if (!$account || !$pwd) {
			$errMsg = '用户名和密码不得为空！';
		} else {
			$sql = 'account = "' . $account . '"';
			$record = $Model -> where($sql) -> find();
			if (!$record) {
				$errMsg = '用户名不存在！';
			} else {
				if ($record['pwd'] != buildPassword($account, $pwd)) {
					$errMsg = '密码不正确！';
				} else {
					$data = array(
							'last_login_time' => time(),
							'last_login_ip'   => getIpAddress(),
							'login_times'     => $record['login_times'] + 1
					);
					
					$Model -> where($sql) -> save($data);
					
					session(C('USER_AUTH_KEY'), $record['id']);
					session('customer', $account);
					session('email', $record['email']);
					session('vip_level', $record['vip_level']);
					
					$ret = 1;
				}
			}
		}
		
		echo json_encode(array('ret'=>$ret, 'errMsg'=>$errMsg));
	}
	
	/**
	 * 用户退出
	 */
	public function doLogout() {
		$id = session(C('USER_AUTH_KEY'));
	
		if ($id) {
			session(C('USER_AUTH_KEY'), null);
			session('customer', null);
			session('email', null);
			session('vip_level', null);
				
			session_destroy();
			$this -> redirect('/Index/index');
		} else {
			$this -> error('已经退出！');
		}
	
	}
	
	
}